package middleware

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"web_framework/pkg/e"
	"web_framework/pkg/errno"
	"web_framework/router/api"
	"web_framework/service"
)

// 检测版本号
func CheckVer () gin.HandlerFunc{
	return func(c *gin.Context){
		sVer := c.Query("sver")
		err := e.CheckVersion(sVer)
		if err != nil {
			c.Abort()
			api.SendResponse(c, err, nil)
			return
		}
		c.Next()
	}
}

func CheckToken () gin.HandlerFunc{
	return func(c *gin.Context){
		uidStr := c.Query("uid")
		if uidStr != "" {
			uid, _ := strconv.Atoi(uidStr)
			token := c.Query("token")
			err, bo := service.CheckUserToken(uid, token)
			if !bo || err != nil {
				c.Abort()
				api.SendResponse(c, errno.ErrTokenInvalid, nil)
				return
			}
		}
		c.Next()
	}
}

func TrackLog() gin.HandlerFunc{
	return func(c *gin.Context){
		e.Log("Info", " [Start Function]: ", c.Request.URL.Path )
		e.Log("Info", " [params]: ", c.Request.URL.RawQuery )
		c.Next()
	}
}